package study.cell_game.objects;

import java.util.ArrayList;
import java.util.List;

import org.andengine.entity.sprite.Sprite;

import study.cell_game.activity.GameActivity;
import study.cell_game.enums.PlayerColor;
import study.cell_game.objects.textures.TokenTextures;
import study.cell_game.objects.tokens.Token;
import study.cell_game.scenes.GameScene;

public class Hand {
	private final static int MAX_TOKENS_ON_HAND = 5;
	private List<Token> tokensOnHand;
	

	private List<Cell> slots;
	private PlayerColor owner;
	
	public Hand(PlayerColor owner){
		this.owner = owner;
		this.tokensOnHand = new ArrayList<Token>();
		this.slots = new ArrayList<Cell>();
		int xIndex = 0;
		if(owner == PlayerColor.RED){
			xIndex = 700;
		}
		for(int i = 0; i<MAX_TOKENS_ON_HAND; i++){
			Cell cell = new Cell(xIndex, 100 * i);
			cell.init();
			this.slots.add(cell);
			GameScene.getInstance().getMainLayer().attachChild(cell.getSprite());
			//GameScene.getInstance().registerTouchArea(cell.getSprite());
		}
	}
	
	public void putTokenOnHand(Token token){
		int index = tokensOnHand.size();
		tokensOnHand.add(token);
		slots.get(index).setToken(token);
		token.setCell(slots.get(index));
		token.setOwner(owner);
		token.startDrawing();
		//GameScene.getInstance().attachChild(
		//		new Sprite(100, 100, TokenTextures.getInstance().getRotate(), GameActivity.main.getVertexBufferObjectManager()));
	      
	}
	
	public List<Token>getTokensOnHand(){ 
		return this.tokensOnHand; 
	} 
	
	public Token getTokenByGlobalId(int id){
		int index=-1;
		for(int i = 0; i< tokensOnHand.size(); i++) 
		{
			if (tokensOnHand.get(i).getId()==id) index = i;
		}
		return tokensOnHand.get(index);
	}
	
	public void deleteTokenFromHand(int id)
	{
		int index=-1;
		for(int i = 0; i< tokensOnHand.size(); i++) 
		{
			if (tokensOnHand.get(i).getId()==id) index = i;
		}
		tokensOnHand.remove(index);
		
		//updating tokens positions on hand
		for (int i = 0; i< tokensOnHand.size(); i++)
		{
			tokensOnHand.get(i).setCell(slots.get(i));
			tokensOnHand.get(i).getPlayerColor().setX(slots.get(i).X);
			tokensOnHand.get(i).getPlayerColor().setY(slots.get(i).Y);
		}
		//removing taken slot from hand.
		slots.get(index).setToken(null);
	}
	
	public int emptySlotsCount(){
		return MAX_TOKENS_ON_HAND - tokensOnHand.size();
	}
}
